package com.xtgg.baby;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.RequestParams;
import com.umeng.analytics.MobclickAgent;
import com.xtgg.R;
import com.xtgg.login.LoginActivity;
import com.xtgg.manager.BaseActivity;
import com.xtgg.model.Resp;
import com.xtgg.sys.Constants;
import com.xtgg.sys.DemoApp;
import com.xtgg.util.MgqDataHandler;
import com.xtgg.util.MgqRestClient;
import com.xtgg.util.PreferencesUtils;
import com.xtgg.util.TLog;
import com.xtgg.util.ToastUtil;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class VetifyCodeActivity extends BaseActivity {
	int mSecond = 300;
	Timer mTimer;
	private SmsObserver smsObserver;

	class SmsObserver extends ContentObserver {
		public SmsObserver(Context context, Handler handler) {
			super(handler);
		}

		@Override
		public void onChange(boolean selfChange) {
			super.onChange(selfChange);
			getSmsFromPhone();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tel_code);
		
		((EditText) findViewById(R.id.etTel)).setEnabled(false);
		((EditText) findViewById(R.id.etTel)).setText(PreferencesUtils.getString(this, "telephone"));

		findViewById(R.id.left).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});

		((TextView) findViewById(R.id.center)).setText("获取设备密码");
		MobclickAgent.onEvent(this, ((TextView) findViewById(R.id.center))
				.getText().toString());
		findViewById(R.id.code).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getCode("4");
			}
		});

		findViewById(R.id.login).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				vetifyCode();
			}
		});

		smsObserver = new SmsObserver(this, smsHandler);
		getContentResolver().registerContentObserver(
				Uri.parse("content://sms/"), true, smsObserver);
	}

	public Handler smsHandler = new Handler() {
		public void handleMessage(Message msg) {
			((EditText) findViewById(R.id.etPwd)).setText((String) msg.obj);
		}
	};

	public void onDestroy() {
		super.onDestroy();
		getContentResolver().unregisterContentObserver(smsObserver);
	}

	public void getSmsFromPhone() {
		ContentResolver cr = getContentResolver();
		String[] projection = new String[] { "body" };// "_id", "address",
														// "person",, "date",
														// "type
		String where = " address='106900467366' AND date >  "
				+ (System.currentTimeMillis() - 60 * 1000);
		Cursor cur = cr.query(Uri.parse("content://sms/"), projection, where,
				null, "date desc");
		if (null == cur)
			return;

		if (cur.moveToNext()) {
			String body = cur.getString(cur.getColumnIndex("body"));
			// 这里我是要获取自己短信服务号码中的验证码~~
			Pattern pattern = Pattern.compile("[0-9]{6}");
			Matcher matcher = pattern.matcher(body);
			if (matcher.find()) {
				String res = matcher.group();
				smsHandler.sendMessage(smsHandler.obtainMessage(0, res));
			}
		}
	}

	/**
	 * 验证手机格式
	 */
	public static boolean isMobileNO(String mobiles) {
		String telRegex = "[1][34578]\\d{9}";
		if (TextUtils.isEmpty(mobiles))
			return false;
		else
			return mobiles.matches(telRegex);
	}

	private void getCode(String type) {
		String tel = ((EditText) findViewById(R.id.etTel)).getText().toString();
		if (!isMobileNO(tel)) {
			Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_LONG).show();
			return;
		}

		MgqDataHandler loginHandler = new MgqDataHandler(this,
				true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);
				if (ruser.getState().equals("1")) {
					final Handler handle = new Handler() {
						public void handleMessage(Message msg) {
							if (mSecond == 0) {
								mSecond = 300;

								findViewById(R.id.code).setOnClickListener(
										new OnClickListener() {
											public void onClick(View v) {
												getCode("4");
											}
										});
								((Button) findViewById(R.id.code))
										.setText("获取验证码");
								((Button) findViewById(R.id.code))
										.setSelected(false);
							} else {
								((Button) findViewById(R.id.code))
										.setOnClickListener(null);
								((Button) findViewById(R.id.code))
										.setText(mSecond + "秒");
								((Button) findViewById(R.id.code))
										.setSelected(true);
							}
						}
					};

					findViewById(R.id.code).setOnClickListener(
							new OnClickListener() {
								public void onClick(View v) {
									getCode("4");
								}
							});

					mTimer = new Timer();
					mTimer.schedule(new TimerTask() {
						@Override
						public void run() {
							mSecond--;
							if (mSecond == 0)
								mTimer.cancel();
							handle.sendEmptyMessage(0);
						}
					}, 0, 1000);
				}
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} else {
					showToast(ruser.getMessage());
				}
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "getCaptcha");
		params.put("type", type);
		params.put("mobile", tel);
		MgqRestClient.get(Constants.USERMGT, params, loginHandler);
	}

	private void vetifyCode() {
		final String tel = ((EditText) findViewById(R.id.etTel)).getText()
				.toString();
		final String code = ((EditText) findViewById(R.id.etPwd)).getText()
				.toString();
		if (!isMobileNO(tel)) {
			Toast.makeText(this, "请输入有效的手机号码", Toast.LENGTH_LONG).show();
			return;
		}

		if (code.length() == 0) {
			Toast.makeText(this, "请输入手机验证码", Toast.LENGTH_LONG).show();
			return;
		}

		MgqDataHandler loginHandler = new MgqDataHandler(this,
				true, false) {
			@Override
			public void onSuccess(String response) {
				TLog.d(TAG, "response=" + response);
				Resp ruser = JSON.parseObject(response, Resp.class);
				if (ruser.getState().equals("1")) {
					Intent intent = new Intent(VetifyCodeActivity.this,
							DevicePwdActivity.class);
					intent.putExtra("password", getIntent().getStringExtra("password"));
					startActivity(intent);

					finish();
				}
				else if (ruser.getState().equals("2"))
				{
					showExitDialog();
				} 
				else {
					showToast(ruser.getMessage());
				}
			}

			public void onFailure(Throwable ble) {
				if (ble != null)
					showToast("网络连接失败");
			}
		};

		RequestParams params = new RequestParams();
		params.put("act", "isCaptcha");
		params.put("captcha", code);
		params.put("mobile", tel);
		MgqRestClient.get(Constants.USERMGT, params, loginHandler);
	}
}
